/**
 * 用户状态管理
 * @author Wu.Liang
 * @date 2025-01-21
 */

import { defineStore } from 'pinia'
import userApi from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户详细信息
    userDetail: null,
    // 用户基本信息（从authStore同步）
    userInfo: null,
    // 用户设置
    settings: {
      // 通知设置
      notification: {
        push: true,
        sms: false,
        email: false
      },
      // 隐私设置
      privacy: {
        showPhone: true,
        showEmail: false,
        showAddress: false
      },
      // 主题设置
      theme: {
        mode: 'light', // light, dark, auto
        primaryColor: '#2d8cf0'
      },
      // 语言设置
      language: 'zh-CN'
    },
    // 用户房户信息
    households: [],
    // 用户设备信息
    devices: [],
    // 加载状态
    loading: false,
    // 错误信息
    error: ''
  }),
  
  getters: {
    /**
     * 获取用户名（优先显示昵称，其次用户名）
     */
    userName: (state) => {
      return state.userInfo?.nickname || state.userInfo?.username || state.userDetail?.nickname || state.userDetail?.username || ''
    },
    
    /**
     * 获取用户昵称
     */
    nickname: (state) => {
      return state.userInfo?.nickname || state.userDetail?.nickname || ''
    },
    
    /**
     * 获取用户真实姓名
     */
    realName: (state) => {
      return state.userInfo?.realName || state.userDetail?.realName || ''
    },
    
    /**
     * 获取用户头像
     */
    userAvatar: (state) => {
      return state.userInfo?.avatar || state.userDetail?.avatar || '/static/images/default-avatar.png'
    },
    
    /**
     * 获取用户手机号
     */
    userPhone: (state) => {
      return state.userInfo?.phone || state.userDetail?.phone || ''
    },
    
    /**
     * 获取用户邮箱
     */
    userEmail: (state) => {
      return state.userInfo?.email || state.userDetail?.email || ''
    },
    
    /**
     * 获取用户类型
     */
    userType: (state) => {
      return state.userInfo?.userType || state.userDetail?.userType || ''
    },
    
    /**
     * 获取用户状态
     */
    userStatus: (state) => {
      return state.userInfo?.status || state.userDetail?.status || 1
    },
    
    /**
     * 获取用户角色
     */
    userRoles: (state) => {
      return state.userInfo?.roles || state.userDetail?.roles || []
    },
    
    /**
     * 获取用户权限
     */
    userPermissions: (state) => {
      return state.userInfo?.permissions || state.userDetail?.permissions || []
    },
    
    /**
     * 获取用户房户信息
     */
    currentHousehold: (state) => {
      return state.households.find(h => h.isDefault) || state.households[0]
    },
    
    /**
     * 获取用户完整地址
     */
    fullAddress: (state) => {
      const household = state.currentHousehold
      if (!household) return ''
      
      return `${household.communityName} ${household.buildingName} ${household.unitName} ${household.roomNumber}`
    },
    
    /**
     * 获取用户社区信息
     */
    communityInfo: (state) => {
      const household = state.currentHousehold
      return household ? {
        communityId: household.communityId,
        communityName: household.communityName,
        buildingId: household.buildingId,
        buildingName: household.buildingName,
        unitId: household.unitId,
        unitName: household.unitName,
        roomId: household.roomId,
        roomNumber: household.roomNumber
      } : null
    }
  },
  
  actions: {
    /**
     * 获取登录信息（从本地存储和authStore同步）
     */
    async getLoginInfo() {
      try {
        // 从本地存储获取用户信息
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          this.userInfo = userInfo
        }
        
        // 如果本地没有用户信息，尝试从API获取
        if (!this.userInfo) {
          await this.getUserDetail()
        }
        
        return this.userInfo
      } catch (error) {
        console.error('获取登录信息失败:', error)
        throw error
      }
    },
    
    /**
     * 同步用户信息（从authStore同步）
     */
    syncUserInfo(userInfo) {
      this.userInfo = userInfo
      // 同时保存到本地存储
      if (userInfo) {
        uni.setStorageSync('userInfo', userInfo)
      }
    },
    
    /**
     * 获取用户详细信息
     */
    async getUserDetail() {
      try {
        this.loading = true
        this.error = ''
        
        const response = await userApi.getUserDetail()
        
        if (response.code === 200) {
          this.userDetail = response.data
          // 同时更新userInfo
          this.userInfo = response.data
          // 保存到本地存储
          uni.setStorageSync('userInfo', response.data)
          return response.data
        } else {
          this.error = response.message || '获取用户详情失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '获取用户详情失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 更新用户信息
     * @param {object} userData 用户数据
     */
    async updateUserInfo(userData) {
      try {
        this.loading = true
        this.error = ''
        
        const response = await userApi.updateUserInfo(userData)
        
        if (response.code === 200) {
          // 更新本地用户信息
          if (this.userDetail) {
            this.userDetail = { ...this.userDetail, ...userData }
          }
          
          return response
        } else {
          this.error = response.message || '更新用户信息失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '更新用户信息失败'
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 移动端更新用户个人资料
     * @param {object} userData 用户数据
     */
    async updateUserProfile(userData) {
      try {
        this.loading = true
        this.error = ''
        
        const response = await userApi.userInfoApi.updateUserProfile(userData)
        
        if (response.code === 200) {
          // 更新本地用户信息
          if (this.userDetail) {
            this.userDetail = { ...this.userDetail, ...response.data }
          }
          if (this.userInfo) {
            this.userInfo = { ...this.userInfo, ...response.data }
          }
          
          // 保存到本地存储
          uni.setStorageSync('userInfo', this.userInfo)
          
          return response
        } else {
          this.error = response.message || '更新用户信息失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '更新用户信息失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 上传用户头像
     * @param {string} filePath 文件路径
     */
    async uploadAvatar(filePath) {
      try {
        this.loading = true
        this.error = ''
        
        const response = await userApi.uploadAvatar(filePath)
        
        if (response.code === 200) {
          // 更新本地头像信息
          if (this.userDetail) {
            this.userDetail.avatar = response.data.avatar
          }
          
          return response
        } else {
          this.error = response.message || '上传头像失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '上传头像失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 获取用户房户信息
     */
    async getUserHouseholds() {
      try {
        const response = await userApi.getUserHouseholds()
        
        if (response.code === 200) {
          this.households = response.data || []
          return response.data
        } else {
          throw new Error(response.message || '获取房户信息失败')
        }
      } catch (error) {
        console.error('获取房户信息失败:', error)
        throw error
      }
    },
    
    /**
     * 绑定房户
     * @param {object} householdData 房户数据
     */
    async bindHousehold(householdData) {
      try {
        this.loading = true
        this.error = ''
        
        const response = await userApi.bindHousehold(householdData)
        
        if (response.code === 200) {
          // 重新获取房户信息
          await this.getUserHouseholds()
          
          return response
        } else {
          this.error = response.message || '绑定房户失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message || '绑定房户失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 获取用户设备信息
     */
    async getUserDevices() {
      try {
        const response = await userApi.getUserDevices()
        
        if (response.code === 200) {
          this.devices = response.data || []
          return response.data
        } else {
          throw new Error(response.message || '获取设备信息失败')
        }
      } catch (error) {
        console.error('获取设备信息失败:', error)
        throw error
      }
    },
    
    /**
     * 更新用户设备信息
     * @param {object} deviceData 设备数据
     */
    async updateUserDevice(deviceData) {
      try {
        const response = await userApi.updateUserDevice(deviceData)
        
        if (response.code === 200) {
          // 重新获取设备信息
          await this.getUserDevices()
          
          return response
        } else {
          throw new Error(response.message || '更新设备信息失败')
        }
      } catch (error) {
        console.error('更新设备信息失败:', error)
        throw error
      }
    },
    
    /**
     * 更新用户设置
     * @param {string} category 设置类别
     * @param {object} settings 设置数据
     */
    updateSettings(category, settings) {
      if (this.settings[category]) {
        this.settings[category] = { ...this.settings[category], ...settings }
        
        // 保存到本地存储
        uni.setStorageSync('userSettings', this.settings)
      }
    },
    
    /**
     * 获取用户设置
     * @param {string} category 设置类别
     */
    getSettings(category) {
      return category ? this.settings[category] : this.settings
    },
    
    /**
     * 初始化用户设置
     */
    initSettings() {
      const savedSettings = uni.getStorageSync('userSettings')
      if (savedSettings) {
        this.settings = { ...this.settings, ...savedSettings }
      }
    },
    
    /**
     * 重置用户设置
     */
    resetSettings() {
      this.settings = {
        notification: {
          push: true,
          sms: false,
          email: false
        },
        privacy: {
          showPhone: true,
          showEmail: false,
          showAddress: false
        },
        theme: {
          mode: 'light',
          primaryColor: '#2d8cf0'
        },
        language: 'zh-CN'
      }
      
      // 清除本地存储
      uni.removeStorageSync('userSettings')
    },
    
    /**
     * 清除用户状态
     */
    clearUserState() {
      this.userDetail = null
      this.households = []
      this.devices = []
      this.error = ''
    }
  }
}) 